{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 一个例子"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n",
    "# from pyimagesearch.minivggnet import MiniVGGNet\n",
    "import tensorflow.keras as keras"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "aug = ImageDataGenerator(rotation_range=20, zoom_range=0.15, width_shift_range=0.2, height_shift_range=0.2,\n",
    "                         shear_range=0.15, horizontal_flip=True, fill_mode='nearest')\n",
    "\n",
    "history = model.fit_generator(aug.flow(trainX, trainY, batch_size=BS),\n",
    "                             validation_data=(testX, testY),\n",
    "                             steps_per_epoch=len(trainX)//BS,\n",
    "                             epochs = EPOCHS)\n",
    "```\n",
    "\n",
    "# 常用参数\n",
    "\n",
    "generator：训练数据的数据生成器  \n",
    "validation_data：验证数据，可以定义为数据生成器，也可以定义为正常的数据  \n",
    "steps_per_epoch：这是与fit函数的区别。因为数据生成器是无限循环的，因此 keras无法确定一个epoch何时开始/结束，因此需要这样一个值。  \n",
    "validation_steps：与train相对应。如果验证数据也是由生成器提供，那么也需要这样一个值。  \n",
    "epochs\n",
    "\n",
    "# 自定义的数据生成器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义\n",
    "def image_generator():\n",
    "    while True:\n",
    "        # do some operation go generate X and Y\n",
    "        yield (X, Y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "# 使用\n",
    "gen = image_generator()\n",
    "model.fit_generator(gen,\n",
    "                    steps_per_epoch=len(trainX)//BS,\n",
    "                    epochs = EPOCHS)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
